package com.dongdongshop.mq;

import com.dongdongshop.constant.SeckillConstant;
import com.dongdongshop.mapper.TbSeckillOrderMapper;
import com.dongdongshop.pojo.seckill.TbSeckillGoods;
import com.dongdongshop.pojo.seckill.TbSeckillOrder;
import com.dongdongshop.util.IdWorker;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Component
@RocketMQMessageListener(consumerGroup = "seckill",topic = "createOrder")
public class SeckillListenter implements RocketMQListener<Map> {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private TbSeckillOrderMapper seckillOrderMapper;
    @Override
    public void onMessage(Map map) {
        Long seckillId= Long.parseLong(map.get("seckillId").toString());
        Long userId=Long.parseLong(map.get("userId").toString());

        TbSeckillGoods seckillGoods= (TbSeckillGoods) redisTemplate.boundHashOps(SeckillConstant.SECKILLGOODSLIST).get(seckillId);

        //保存订单
        TbSeckillOrder seckillOrder = new TbSeckillOrder();
        seckillOrder.setUserId(userId.toString());
        seckillOrder.setStatus("0");//待支付
        seckillOrder.setSellerId(seckillGoods.getSellerId());
        seckillOrder.setSeckillId(seckillGoods.getId());
        seckillOrder.setMoney(seckillGoods.getCostPrice());
        seckillOrder.setCreateTime(new Date());
        seckillOrder.setId(idWorker.nextId());
        seckillOrderMapper.insertSelective(seckillOrder);
        //redis存放当前用户待支付的商品订单数据
        redisTemplate.boundHashOps(SeckillConstant.SECKILLORDERList).put(userId,seckillOrder);
        System.out.println("消息消费成功");
    }
}
